package controller;

import com.sun.org.apache.xerces.internal.impl.Constants;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import pojo.SysRole;
import pojo.SysUser;
import service.SysRoleService;
import service.SysUserService;
import utils.Page;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author 崔书健
 * @date 2024/7/26
 */
@Controller
@RequestMapping("/user")
@Scope("prototype")
public class SysUserController {
    private Logger logger = LogManager.getLogger(SysUserController.class);
    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysRoleService sysRoleService;

    // 跳转到登录页面
    @RequestMapping("/toLogin")
    public String login(){
        return "login";
    }
    @RequestMapping("/login")
    public String doLogin(
            @RequestParam(value = "account")String account,
            @RequestParam(value = "password")String password,
            HttpSession session,HttpServletRequest request
    ){
        logger.debug("登录方法");
        // 调用service方法，进行用户匹配
        SysUser sysUser = sysUserService.login(account, password);
        if (null != sysUser){
            // 将登录用户放入session
            session.setAttribute("userSession",sysUser);
            // 登录成功，重定向到/user/toMain接口
            return "redirect:/user/toMain";
        }else {
            request.setAttribute("error","用户名或密码不正确！");
            // 用户不存在，登录失败，跳转到登录页面
            return "login";
        }
    }

    @RequestMapping("/toMain")
    public String main(HttpSession session){
        if (session.getAttribute("userSession") == null){
            // 重定向到登录页面接口
            return "redirect:/user/toLogin";
        }
        return "frame";
    }

    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e,HttpServletRequest request){
        request.setAttribute("e",e);
        return "error";
    }

    @RequestMapping("/exLogin")
    public String exLogin(@RequestParam String account, @RequestParam String password){
        // 调用service方法，进行用户匹配
        SysUser user = sysUserService.login(account,password);
        if (null == user){
            throw new RuntimeException("用户名或者密码不正确，跳转到错误页面!");
        }
        return "redirect:/user/toMain";
    }
    @GetMapping("/list")
    public String getUserList(Model model, String queryRealName, Integer queryRoleId, @RequestParam(defaultValue = "1")Integer pageIndex){
        List<SysUser> userList = null;
        try {
            // 设置页面容量
            int pageSize = 5;
            // 总数量(表)
            int totalCount = sysUserService.count(queryRealName,queryRoleId);
            // 总页数
            Page<SysUser> page = new Page<SysUser>();
            page.setPageNo(pageIndex);
            page.setPageSize(pageSize);
            page.setTotalCount(totalCount);
            int totalPageCount = page.getTotalPage();
            // 控制首页和尾页
            if (pageIndex > totalPageCount){
                pageIndex = totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            userList = sysUserService.selectPage(pageIndex,pageSize,queryRealName,queryRoleId);
            model.addAttribute("userList",userList);
            List<SysRole> roleList = null;
            roleList = sysRoleService.list();
            model.addAttribute("roleList",roleList);
            model.addAttribute("queryRealName",queryRealName);
            model.addAttribute("queryRoleId",queryRoleId);
            model.addAttribute("totalPageCount",totalPageCount);
            model.addAttribute("totalCount",totalCount);
            model.addAttribute("currentPageNo",pageIndex);
        } catch (RuntimeException e) {
            e.printStackTrace();
            logger.error("用户列表接口访问失败");
            return "redirect:/user/toSysError";
        }
        return "sysUser/list";
    }

    // 跳转到异常处理页面
    @RequestMapping(value = "/toSysError")
    public String sysError(){
        return "sysError";
    }
//    private ArrayList<SysUser> userList = new ArrayList<SysUser>();
//    // 用于返回查询到的用户数据
//    private ArrayList<SysUser> queryUserList = new ArrayList<SysUser>();
//    public SysUserController(){
//        try {
//            userList.add(new SysUser(5,"zhaojing","赵静","5555555",1,"13054784445","上海市宝山区",1,1,new Date(),1,new Date()));
//            userList.add(new SysUser(4,"wanglin","王林","4444444",1,"18965652364","北京市学院路",1,1,new Date(),1,new Date()));
//            userList.add(new SysUser(1,"test001","测试用户001","1111111",1,"13566669998","北京市朝阳区",1,1,new Date(),1,new Date()));
//            userList.add(new SysUser(2,"zhaoyan","赵燕","2222222",1,"18678786545","北京市海淀区",1,1,new Date(),1,new Date()));
//            userList.add(new SysUser(3,"test003","测试用户003","1111111",1,"13121334531","上海市宝山区",1,1,new Date(),1,new Date()));
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//    }
//
//    @GetMapping("/list")
//    public String list(Model model, HttpServletRequest request){
//        logger.info("当查询条件为空时，查询用户信息" + this);
//        queryUserList.clear();
//        queryUserList.addAll(userList);
//        model.addAttribute("queryUserList",userList);
//        request.setAttribute("queryUserList",userList);
//        return "sysUser/sysUserList";
//    }
//
//    @PostMapping("/list")
//    public String list(@RequestParam(value = "realName",required = false)String realName,Model model,HttpServletRequest request){
//        logger.info("查询条件:【realName】=" + realName + ",查询用户信息");
//        queryUserList.clear();
//        if (realName != null && !realName.equals("")){
//            for (SysUser user : userList){
//                if (user.getRealName().indexOf(realName) != -1){
//                    queryUserList.add(user);
//                }
//            }
//        }else{
//            queryUserList.addAll(userList);
//        }
//        model.addAttribute("queryUserList",queryUserList);
//        model.addAttribute(realName);
//        request.setAttribute("queryUserList",queryUserList);
//        return "sysUser/sysUserList";
//    }
}
